package com.zkw.nio;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * Created by Administrator on 2016/4/30 0030.
 */
public class ClientThread extends Thread {
    private Selector selector;

    public ClientThread(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {
        try{
            while (selector.isOpen() && selector.select()>0){
                for (SelectionKey key: selector.selectedKeys()){
                    SocketChannel socketChannel = (SocketChannel)key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(40);
                    int size = socketChannel.read(byteBuffer);
                    while (size>0){
                        byteBuffer.flip();
                        Charset charset = Charset.forName("UTF-8");
                        System.out.println(charset.newDecoder().decode(byteBuffer));
                        size = socketChannel.read(byteBuffer);
                    }
                    selector.selectedKeys().remove(key);
                }
                selector.close();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
